package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Audio;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


/**
 * dubbo接口实现类
 * 发送语音和接收语音
 */
@Service(version = "1.0.0")
@Slf4j
public class AudioApiImpl implements AudioApi {
    //注入mongodb模板
    @Autowired
    private MongoTemplate mongoTemplate;

    //发送语音
    @Override
    public String sendAudio(String url, Long userId) {
        Audio audio = new Audio();
        audio.setId(ObjectId.get());
        audio.setUseId(userId);
        audio.setUrl(url);
        audio.setCreated(System.currentTimeMillis());
        try {
            //保存到数据库
            mongoTemplate.save(audio);
            return audio.getId().toHexString();
        } catch (Exception e) {
            log.error("保存失败了" + e);
        }
        return null;
    }


    //查询数据库的所有语音
    @Override
    public List<Audio> queryAudioList(int page, int size) {
        //分页条件
        Pageable pageable= PageRequest.of(page-1,size, Sort.by(Sort.Order.desc("created")));
        //查询条件，查询全部
        Query query=new Query().with(pageable);
        List<Audio> audio = mongoTemplate.find(query, Audio.class);
        return audio;

    }
}
